package com.benefm.multipar.pad.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;

import com.benefm.multipar.pad.R;

public class BloodOxygenDashboard extends View {

    // 定义变量
    private Paint backgroundPaint, coloredArcPaint, scalePaint, textPaint, valuePaint;
    private Path heartPath, waveformPath;
    private RectF arcRect;
    private int width, height;
    private float centerX, centerY;
    private float radius;

    // 配置参数
    private float startAngle = 140f;
    private float sweepAngle = 260f;
    private float maxValue = 100f;
    private float currentValue = 95f;
    private int normalColor = Color.parseColor("#29B6F6"); // 蓝色
    private int warningColor = Color.parseColor("#F44336"); // 红色
    private int criticalThreshold = 85; // 警告阈值
    private String title = "OXYGEN";
    private String unit = "%";
    private boolean showHeartIcon = true;
    private boolean showWaveform = true;

    public BloodOxygenDashboard(Context context) {
        super(context);
        init(null);
    }

    public BloodOxygenDashboard(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        // 解析自定义属性
        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.BloodOxygenDashboard);
            normalColor = a.getColor(R.styleable.BloodOxygenDashboard_normalColor, normalColor);
            warningColor = a.getColor(R.styleable.BloodOxygenDashboard_warningColor, warningColor);
            criticalThreshold = a.getInt(R.styleable.BloodOxygenDashboard_criticalThreshold, criticalThreshold);
            title = a.getString(R.styleable.BloodOxygenDashboard_title);
            if (title == null) title = "OXYGEN";
            unit = a.getString(R.styleable.BloodOxygenDashboard_unit);
            if (unit == null) unit = "%";
            showHeartIcon = a.getBoolean(R.styleable.BloodOxygenDashboard_showHeartIcon, true);
            showWaveform = a.getBoolean(R.styleable.BloodOxygenDashboard_showWaveform, true);
            a.recycle();
        }

        // 背景弧线画笔
        backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        backgroundPaint.setStyle(Paint.Style.STROKE);
        backgroundPaint.setStrokeWidth(24f);
        backgroundPaint.setColor(Color.parseColor("#37474F"));
        backgroundPaint.setStrokeCap(Paint.Cap.ROUND);

        // 彩色弧线画笔
        coloredArcPaint = new Paint(backgroundPaint);

        // 刻度线画笔
        scalePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        scalePaint.setStrokeWidth(3f);
        scalePaint.setColor(Color.WHITE);
        scalePaint.setStrokeCap(Paint.Cap.ROUND);

        // 文字画笔
        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setTextSize(30f);
        textPaint.setColor(Color.parseColor("#B0BEC5"));
        textPaint.setTextAlign(Paint.Align.CENTER);

        // 主数值画笔
        valuePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        valuePaint.setTextSize(72f);
        valuePaint.setColor(Color.WHITE);
        valuePaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
        valuePaint.setTextAlign(Paint.Align.CENTER);

        // 心形路径
        heartPath = new Path();

        // 心电图路径
        waveformPath = new Path();

        arcRect = new RectF();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;

        float padding = 24f;
        radius = Math.min(width, height) * 0.35f;
        centerX = width / 2f;
        centerY = height / 2f;

        // 弧形区域
        float arcRadius = radius * 1.1f;
        arcRect.set(
                centerX - arcRadius,
                centerY - arcRadius,
                centerX + arcRadius,
                centerY + arcRadius
        );

        // 构建心形路径
        buildHeartPath();

        // 构建心电图路径
        buildWaveformPath();
    }

    private void buildHeartPath() {
        float heartSize = radius * 0.4f;
        heartPath.reset();

        // 从底部中心开始
        heartPath.moveTo(centerX, centerY + heartSize * 0.4f);

        // 绘制左侧曲线
        heartPath.cubicTo(
                centerX - heartSize * 0.5f, centerY - heartSize * 0.2f,
                centerX - heartSize * 0.9f, centerY - heartSize * 0.5f,
                centerX - heartSize * 0.35f, centerY - heartSize * 0.6f
        );

        // 绘制顶部曲线
        heartPath.cubicTo(
                centerX, centerY - heartSize * 0.9f,
                centerX + heartSize * 0.35f, centerY - heartSize * 0.6f,
                centerX + heartSize * 0.35f, centerY - heartSize * 0.6f
        );

        // 绘制右侧曲线
        heartPath.cubicTo(
                centerX + heartSize * 0.9f, centerY - heartSize * 0.5f,
                centerX + heartSize * 0.5f, centerY - heartSize * 0.2f,
                centerX, centerY + heartSize * 0.4f
        );

        heartPath.close();
    }

    private void buildWaveformPath() {
        float waveHeight = radius * 0.2f;
        float startX = centerX - radius * 0.7f;
        float startY = centerY + radius * 0.15f;

        waveformPath.reset();
        waveformPath.moveTo(startX, startY);

        // 随机生成心电图波形
        waveformPath.lineTo(startX + radius * 0.2f, startY - waveHeight * 0.3f);
        waveformPath.lineTo(startX + radius * 0.3f, startY + waveHeight * 0.4f);
        waveformPath.lineTo(startX + radius * 0.4f, startY - waveHeight * 0.2f);
        waveformPath.lineTo(startX + radius * 0.5f, startY + waveHeight * 0.3f);
        waveformPath.lineTo(startX + radius * 0.7f, startY);
        waveformPath.lineTo(startX + radius * 0.8f, startY - waveHeight * 0.5f);
        waveformPath.lineTo(startX + radius * 0.9f, startY + waveHeight * 0.6f);
        waveformPath.lineTo(startX + radius * 1.1f, startY - waveHeight * 0.3f);
        waveformPath.lineTo(startX + radius * 1.3f, startY);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 1. 绘制背景弧线
        canvas.drawArc(arcRect, startAngle, sweepAngle, false, backgroundPaint);

        // 2. 绘制彩色弧线
        float criticalPosition = startAngle + (criticalThreshold / maxValue) * sweepAngle;
        float sweepNormal = (criticalThreshold / maxValue) * sweepAngle;

        // 正常区域（蓝色）
        coloredArcPaint.setColor(normalColor);
        canvas.drawArc(arcRect, startAngle, sweepNormal, false, coloredArcPaint);

        // 警告区域（红色）
        if (currentValue > criticalThreshold) {
            float warningSweep = ((currentValue - criticalThreshold) / maxValue) * sweepAngle;
            coloredArcPaint.setColor(warningColor);
            canvas.drawArc(arcRect, criticalPosition, warningSweep, false, coloredArcPaint);
        }

        // 3. 绘制刻度线
        drawScales(canvas);

        // 4. 绘制心形图标
        if (showHeartIcon) {
            Paint heartPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            heartPaint.setStyle(Paint.Style.FILL);
            heartPaint.setColor(warningColor);
            canvas.drawPath(heartPath, heartPaint);
        }

        // 5. 绘制心电图
        if (showWaveform) {
            Paint wavePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            wavePaint.setStyle(Paint.Style.STROKE);
            wavePaint.setStrokeWidth(4f);
            wavePaint.setColor(Color.WHITE);
            canvas.drawPath(waveformPath, wavePaint);
        }

        // 6. 绘制主数值
        String valueText = String.format("%.0f", currentValue);
        float textHeight = valuePaint.descent() - valuePaint.ascent();
        canvas.drawText(valueText, centerX, centerY + textHeight / 4, valuePaint);

        // 7. 绘制单位和标题
        canvas.drawText(unit, centerX, centerY + textHeight, textPaint);
        canvas.drawText(title, centerX, centerY + textHeight * 1.6f, textPaint);
    }

    private void drawScales(Canvas canvas) {
        int majorScales = 6; // 主刻度数量
        float scaleLength = radius * 0.15f;

        for (int i = 0; i <= majorScales; i++) {
            float value = i * (maxValue / majorScales);
            float angle = startAngle + (sweepAngle * i / majorScales);
            float angleRad = (float) Math.toRadians(angle);

            // 计算位置
            float startX = (float) (centerX + radius * 0.95f * Math.cos(angleRad));
            float startY = (float) (centerY + radius * 0.95f * Math.sin(angleRad));
            float endX = (float) (centerX + (radius * 0.95f - scaleLength) * Math.cos(angleRad));
            float endY = (float) (centerY + (radius * 0.95f - scaleLength) * Math.sin(angleRad));

            // 绘制主刻度线
            canvas.drawLine(startX, startY, endX, endY, scalePaint);

            // 绘制刻度值
            if (i > 0 && i < majorScales) {
                float textRadius = radius * 0.75f;
                float textX = (float) (centerX + textRadius * Math.cos(angleRad));
                float textY = (float) (centerY + textRadius * Math.sin(angleRad)) + 12;
                canvas.drawText(String.valueOf((int) value), textX, textY, textPaint);
            }
        }

        // 添加小刻度
        int minorScales = majorScales * 5;
        for (int i = 0; i <= minorScales; i++) {
            if (i % 5 == 0) continue; // 跳过主刻度

            float angle = startAngle + (sweepAngle * i / minorScales);
            float angleRad = (float) Math.toRadians(angle);

            float minorLength = scaleLength * 0.6f;
            float startX = (float) (centerX + radius * 0.95f * Math.cos(angleRad));
            float startY = (float) (centerY + radius * 0.95f * Math.sin(angleRad));
            float endX = (float) (centerX + (radius * 0.95f - minorLength) * Math.cos(angleRad));
            float endY = (float) (centerY + (radius * 0.95f - minorLength) * Math.sin(angleRad));

            canvas.drawLine(startX, startY, endX, endY, scalePaint);
        }
    }

    // 设置当前值（带动画）
    public void setValue(float value) {
        if (value > maxValue) value = maxValue;
        if (value < 0) value = 0;

        ValueAnimator animator = ValueAnimator.ofFloat(currentValue, value);
        animator.setDuration(1500);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.addUpdateListener(animation -> {
            currentValue = (float) animation.getAnimatedValue();
            invalidate();
        });
        animator.start();
    }

    public void setTitle(String title) {
        this.title = title;
        invalidate();
    }

    public void setUnit(String unit) {
        this.unit = unit;
        invalidate();
    }

    public void setCriticalThreshold(int threshold) {
        this.criticalThreshold = threshold;
        invalidate();
    }

    public void setNormalColor(int color) {
        this.normalColor = color;
        invalidate();
    }

    public void setWarningColor(int color) {
        this.warningColor = color;
        invalidate();
    }

    public void showHeartIcon(boolean show) {
        this.showHeartIcon = show;
        invalidate();
    }

    public void showWaveform(boolean show) {
        this.showWaveform = show;
        invalidate();
    }

}
